# 服务器Windows服务安装脚本
# 此脚本需要以管理员身份在服务器上运行
param(
    [switch]$Install,
    [switch]$Uninstall,
    [switch]$Start,
    [switch]$Stop,
    [switch]$Restart,
    [switch]$Status
)

$serviceName = "LzfyHisService"
$serviceDisplayName = "HIS退费审核服务"
$serviceDescription = "HIS退费审核管理系统后台服务"
$exePath = "D:\Service\Lzfy_His_Service\Lzfy_His_Service.exe"

Write-Host "=== HIS退费服务管理 ===" -ForegroundColor Green
Write-Host "服务名称: $serviceName" -ForegroundColor Cyan
Write-Host "服务路径: $exePath" -ForegroundColor Cyan

# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "请以管理员身份运行此脚本" -ForegroundColor Red
    Write-Host "右键点击PowerShell图标 -> 以管理员身份运行" -ForegroundColor Yellow
    exit 1
}

function Install-Service {
    Write-Host "安装Windows服务..." -ForegroundColor Green
    
    # 检查服务是否已存在
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        Write-Host "服务已存在，先卸载..." -ForegroundColor Yellow
        Uninstall-Service
    }
    
    # 检查可执行文件
    if (-not (Test-Path $exePath)) {
        Write-Host "错误: 可执行文件不存在: $exePath" -ForegroundColor Red
        Write-Host "请确保服务已正确部署到 D:\Service\Lzfy_His_Service" -ForegroundColor Yellow
        exit 1
    }
    
    Write-Host "创建服务..." -ForegroundColor Yellow
    
    # 创建服务
    $result = & sc.exe create $serviceName binPath= "$exePath" DisplayName= "$serviceDisplayName" start= auto obj= LocalSystem
    if ($LASTEXITCODE -ne 0) {
        Write-Host "创建服务失败: $result" -ForegroundColor Red
        exit 1
    }
    
    # 设置服务描述
    & sc.exe description $serviceName $serviceDescription
    
    # 设置服务失败恢复策略
    & sc.exe failure $serviceName reset= 86400 actions= restart/60000/restart/60000/restart/60000
    
    # 设置服务依赖
    & sc.exe config $serviceName depend= HTTP/TCPIP
    
    Write-Host "服务安装成功" -ForegroundColor Green
    Write-Host "服务名称: $serviceName" -ForegroundColor Cyan
    Write-Host "显示名称: $serviceDisplayName" -ForegroundColor Cyan
    
    # 显示服务信息
    Get-Service -Name $serviceName | Format-Table Name, Status, StartType
    
    Write-Host "启动服务: .\install-service-server.ps1 -Start" -ForegroundColor Yellow
}

function Uninstall-Service {
    Write-Host "卸载Windows服务..." -ForegroundColor Yellow
    
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        # 停止服务
        if ($service.Status -eq 'Running') {
            Write-Host "停止服务..." -ForegroundColor Yellow
            Stop-Service -Name $serviceName -Force
            Start-Sleep -Seconds 2
        }
        
        # 删除服务
        Write-Host "删除服务..." -ForegroundColor Yellow
        & sc.exe delete $serviceName
        
        # 等待服务删除完成
        Start-Sleep -Seconds 3
        
        Write-Host "服务已卸载" -ForegroundColor Green
    } else {
        Write-Host "服务不存在" -ForegroundColor Yellow
    }
}

function Start-ServiceMode {
    Write-Host "启动服务..." -ForegroundColor Green
    
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if (-not $service) {
        Write-Host "服务未安装，请先安装服务" -ForegroundColor Red
        return
    }
    
    if ($service.Status -eq 'Running') {
        Write-Host "服务已在运行中" -ForegroundColor Green
    } else {
        Start-Service -Name $serviceName
        Write-Host "服务启动成功" -ForegroundColor Green
    }
    
    # 等待服务启动
    Start-Sleep -Seconds 2
    
    # 显示状态
    Get-Service -Name $serviceName | Format-Table Name, Status, StartType
    
    # 检查端口
    $portInUse = Get-NetTCPConnection -LocalPort 6729 -ErrorAction SilentlyContinue
    if ($portInUse) {
        Write-Host "服务端口 6729 正在使用" -ForegroundColor Green
    } else {
        Write-Host "警告: 服务端口 6729 未使用" -ForegroundColor Yellow
    }
}

function Stop-ServiceMode {
    Write-Host "停止服务..." -ForegroundColor Yellow
    
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service -and $service.Status -eq 'Running') {
        Stop-Service -Name $serviceName -Force
        Write-Host "服务已停止" -ForegroundColor Green
    } else {
        Write-Host "服务未运行" -ForegroundColor Yellow
    }
    
    Get-Service -Name $serviceName | Format-Table Name, Status, StartType
}

function Restart-ServiceMode {
    Write-Host "重启服务..." -ForegroundColor Yellow
    
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        Restart-Service -Name $serviceName
        Write-Host "服务重启成功" -ForegroundColor Green
        Start-Sleep -Seconds 2
        Get-Service -Name $serviceName | Format-Table Name, Status, StartType
    } else {
        Write-Host "服务未安装" -ForegroundColor Red
    }
}

function Get-ServiceStatus {
    Write-Host "检查服务状态..." -ForegroundColor Cyan
    
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        Write-Host "Windows服务:" -ForegroundColor Cyan
        $service | Format-Table Name, Status, StartType
        
        # 检查进程
        $processes = Get-Process -Name "Lzfy_His_Service" -ErrorAction SilentlyContinue
        if ($processes) {
            Write-Host "进程信息:" -ForegroundColor Cyan
            $processes | Format-Table Id, ProcessName, CPU, WorkingSet
        }
        
        # 检查端口
        $portInUse = Get-NetTCPConnection -LocalPort 6729 -ErrorAction SilentlyContinue
        if ($portInUse) {
            Write-Host "端口 6729 正在使用" -ForegroundColor Green
        } else {
            Write-Host "端口 6729 未使用" -ForegroundColor Yellow
        }
        
        # 检查日志
        $logPath = "D:\Service\Lzfy_His_Service\logs\service-$(Get-Date -Format 'yyyyMMdd').log"
        if (Test-Path $logPath) {
            $logSize = [math]::Round((Get-Item $logPath).Length / 1MB, 2)
            Write-Host "日志文件: $logPath ($logSize MB)" -ForegroundColor Cyan
            
            # 显示最后几行日志
            Write-Host "最后10行日志:" -ForegroundColor Yellow
            Get-Content $logPath -Tail 10 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
        }
    } else {
        Write-Host "服务未安装" -ForegroundColor Red
    }
}

# 执行操作
switch ($true) {
    $Install { Install-Service }
    $Uninstall { Uninstall-Service }
    $Start { Start-ServiceMode }
    $Stop { Stop-ServiceMode }
    $Restart { Restart-ServiceMode }
    $Status { Get-ServiceStatus }
    default {
        Write-Host "使用方法:" -ForegroundColor Cyan
        Write-Host "  .\install-service-server.ps1 -Install     # 安装服务" -ForegroundColor Yellow
        Write-Host "  .\install-service-server.ps1 -Uninstall  # 卸载服务" -ForegroundColor Yellow
        Write-Host "  .\install-service-server.ps1 -Start      # 启动服务" -ForegroundColor Yellow
        Write-Host "  .\install-service-server.ps1 -Stop       # 停止服务" -ForegroundColor Yellow
        Write-Host "  .\install-service-server.ps1 -Restart    # 重启服务" -ForegroundColor Yellow
        Write-Host "  .\install-service-server.ps1 -Status     # 查看状态" -ForegroundColor Yellow
    }
}